package top.codedance.iotp.registy.net.handle.action;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.ServerMeta;
import top.codedance.iotp.common.enums.HttpStatus;
import top.codedance.iotp.registy.RegistryApplication;
import top.codedance.iotp.registy.net.handle.AdapterController;
import org.apache.log4j.Logger;

public class ServerMetaController extends AdapterController {
    private static Logger logger = RegistryApplication.getLogger(ServerMetaController.class);

    public String doSubHandler(JSONObject body) {
        try {
            String deviceId = body.getString("deviceId");
            if(RegistryApplication.checkClient(deviceId)){
                String serverKey = RegistryApplication.getClient(deviceId);
                if(serverKey != null){
                    ServerMeta serverMeta = RegistryApplication.getServer(serverKey);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("bindIp", serverMeta.getBindIp());
                    jsonObject.put("httpBindHost", serverMeta.getHttpBindHost());
                    jsonObject.put("wsBindHost", serverMeta.getWsBindHost());
                    jsonObject.put("tcpPort", serverMeta.getTcpPort());
                    jsonObject.put("httpPort", serverMeta.getHttpPort());
                    jsonObject.put("wsPort", serverMeta.getWsPort());
                    return okResponse(jsonObject);
                }else{
                    RegistryApplication.delClient(deviceId);
                    return errResponse(HttpStatus.NOT_FOUND.getCode(), "not found.");
                }
            }else{
                return errResponse(HttpStatus.NOT_FOUND.getCode(), "not found.");
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return response500( "Programe exception");
        }
    }
}
